package com.prothink.threadadmindemo.controller;

public class PrintOddEven {
    private int number = 0;
    private final Object lock = new Object();

    public void printOdd() {
        while (number <= 100) {
            synchronized (lock) {
                if (number % 2 == 0) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    System.out.println(Thread.currentThread().getName() + ": " + number++);
                    lock.notify();
                }
            }
        }
    }

    public void printEven() {
        while (number <= 100) {
            synchronized (lock) {
                if (number % 2 != 0) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    System.out.println(Thread.currentThread().getName() + ": " + number++);
                    lock.notify();
                }
            }
        }
    }

    public static void main(String[] args) {
        PrintOddEven printOddEven = new PrintOddEven();
        Thread oddThread = new Thread(printOddEven::printOdd);
        Thread evenThread = new Thread(printOddEven::printEven);
        oddThread.start();
        evenThread.start();
    }
}

